package cn.hls.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hls.dao.OrgDao;
import cn.hls.entity.Org;
import cn.hls.entity.vo.ExtTree;
import cn.hls.entity.vo.PageInfo;
import cn.hls.exception.BussinessException;
import cn.hlsconstant.DataAssessEnum;

/**
 * @fileName: OrgDaoImpl.java
 * @package: com.bangni.dao.impl
 * @Description: 组织机构数据接口实现类
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date: 2015-5-1
 */
@Component("orgDao")
public class OrgDaoImpl extends BaseDaoImpl<Org> implements OrgDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<ExtTree> loadChildOrgInfo(Org org, Object nodeId) throws Exception {
		StringBuilder selectHql = new StringBuilder();
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("select new cn.hls.entity.vo.ExtTree(f.name ,f.id,f.code,(select case when count(id) = 0 then true else false end from Org  where deleted=false and parent.id=f.id) as leaf) from Org f where deleted=?  ");
		paramList.add(false);
		if (nodeId == null)
			selectHql.append(" and parent.id is null");
		else {
			if ((Long) nodeId != 0L) {
				selectHql.append(" and parent.id=?");
				paramList.add(nodeId);
			}
		}
		if ((org != null) && (StringUtils.hasText(org.getName()))) {
			selectHql.append(" and name like ?");
			paramList.add("%" + org.getName() + "%");
		}
		selectHql.append(" order by sort");
		return (List<ExtTree>) find(selectHql.toString(), paramList.toArray());
	}

	@Override
	public PageInfo<Org> loadOrgInfo(Org entity, PageInfo<Org> page) throws Exception {
		// 定义查询Hql语句
		StringBuilder selectHql = new StringBuilder();
		// 定义汇总Hql语句
		StringBuilder counthql = new StringBuilder();
		// 定义查询参数
		List<Object> paramList = new ArrayList<Object>();
		selectHql.append("from Org where  deleted=? ");
		paramList.add(false);
		if (entity != null) {
			Long fatherId = entity.getId();
			if (fatherId == null || fatherId == 0)
				selectHql.append(" and  parent.id is null ");
			else {
				selectHql.append(" and  parent.id=?");
				paramList.add(fatherId);
			}
			if (StringUtils.hasText(entity.getName())) {
				selectHql.append(" and name like ?");
				paramList.add("%" + entity.getName().trim() + "%");
			}
		}
		counthql.append(" select count(id) ").append(selectHql);
		selectHql.append(" order by sort");
		return find(selectHql.toString(), counthql.toString(), paramList.toArray(), page);
	}

	@Override
	public Org findOrg(String name, String code,Long parentId) throws Exception {
		StringBuilder hql = new StringBuilder("from Org m where (m.name = ? or m.code=?) and  deleted=?  " );
		List<Object> params=new ArrayList<Object>();
		params.add(name);
		params.add(code);
		params.add(false);
		if(parentId!=null){
			hql.append("and m.parent.id=? ");
			params.add(parentId);
		}
		Query query = getSession().createQuery(hql.toString());
		for(int i=0;i<params.size();i++){
			query.setParameter(i, params.get(i));
		}
		Org org = (Org) query.uniqueResult();
		return org;
	}

	@Override
	public String deleteOrg(Long id) throws Exception {
		try {
			Org org = (Org) find(id);
			if (checkChildren(id)) {
				return "[" + org.getName() + "] 存在有子组织,不允许删除！";
			}
			super.delete(id);
			return "ok";
		} catch (Exception e) {
			throw new BussinessException(DataAssessEnum.DELETE_ERROR, "组织数据删除失败");
		}
	}

	/**
	 * 根据编号查询模块是否存在子模块信息
	 * 
	 * @param id编号
	 * @return boolean
	 */
	private boolean checkChildren(Long id) throws Exception {
		String hql = "select count(id) from Org where parent.id=? and deleted=? ";
		return ((Long) getSession().createQuery(hql).setParameter(0, id).setParameter(1, false).uniqueResult()).longValue() > 0L;
	}

	@Override
	public void updateOrgSort(String ids) throws Exception {
		String[] tempIds = ids.split(",");
		for (int i = 0; i < tempIds.length; i++) {
			String hql = "update Org set sort=? where id=?";
			executeHQLUpdate(hql, new Object[] { i + 1, Long.valueOf(tempIds[i]) });
		}

	}

	@Override
	public Map<String, Long> loadOrgInfo() throws Exception {
		String hql="select new Org(id,name) from Org where deleted=?";
		List<Org>list=findByHql(hql, new Object[]{false});
		Map <String,Long>map=new HashMap<String, Long>();
		for(Org item:list){
			map.put(item.getName(), item.getId());
		}
		return map;
	}
 
}
